﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Common;
using Common.Attribute;
using Model;
using Model.DtoModel;
using Model.EasyUiModel;
using Model.ViewModel;
using MvcOa.Helper;
using MvcOa.Logic.Admin.Filter;

namespace MvcOa.Logic.Admin
{
    [AdminAuthorize]
    public class PermissionController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        [Ajax]
        public ActionResult GetPermissionListTree()
        {
            return Json(OperationContext.Current.ListPermissionTreeNodeModels, JsonRequestBehavior.AllowGet);
        }

        //public ActionResult SonPermission(int id)
        //{
        //    ViewBag.ParentId = id;
        //    return View("~/Areas/Admin/Views/System/SonPermission.cshtml");
        //}
        [HttpPost]
        public ActionResult GetPermissionList()
        {
            int pageSize = RequestHelper.GetInt("rows");
            int pageIndex = RequestHelper.GetInt("page");
            //List<Permission> listPermissions = OperationContext.Current.IBllSession.IPermissionBll.GetListBy(m => m.pIsDel == false).ToList().Select(m => m.ToPoco()).ToList();
            int pParent = RequestHelper.GetInt("parendId",1);
            List<Permission> listPermissions = null;
            int count = 0;
            if (pParent == 10000)
            {
                //列出全部权限
                listPermissions =
                    OperationContext.Current.IBllSession.IPermissionBll.GetPagedList(pageIndex,
                     pageSize, m => m.pIsDel == false, p => p.pid, out count).ToList().Select(m => m.ToPoco()).ToList();
            }
            else
            {
                listPermissions =
                 OperationContext.Current.IBllSession.IPermissionBll.GetPagedList(pageIndex,
                     pageSize, m => m.pIsDel == false && m.pParent == pParent, p => p.pid, out count).ToList().Select(m => m.ToPoco()).ToList();
            }
            DataGridModel dataGridModel = new DataGridModel()
            {
                total = count,
                footer = null,
                rows = listPermissions
            };
            return Json(dataGridModel);
        }

        [HttpGet]
        public ActionResult EditPermission(int id)
        {
            PermissionViewModel viewModel =
                OperationContext.Current.IBllSession.IPermissionBll.GetListBy(m => m.pid == id).ToList()
                .Select(m => new PermissionViewModel()
                {
                    pActionName = m.pActionName,
                    pAreaName = m.pAreaName,
                    pControllerName = m.pControllerName,
                    pFormMethod = m.pFormMethod,
                    pid = m.pid,
                    pIsShow = m.pIsShow,
                    pName = m.pName,
                    pOperationType = m.pOperationType,
                    pParent = m.pParent,
                    pRemark = m.pRemark
                }).FirstOrDefault();

            BuildDropDownList();
            return PartialView("EditPermission", viewModel);
        }

        [HttpPost]
        public ActionResult EditPermission(PermissionViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                if (viewModel!=null&&viewModel.pid!=0)
                {
                    Permission permission = new Permission()
                    {
                        pid = viewModel.pid,
                        pActionName = viewModel.pActionName,
                        pAddTime = DateTime.Now,
                        pAreaName = viewModel.pAreaName,
                        pControllerName = viewModel.pControllerName,
                        pFormMethod = viewModel.pFormMethod,
                        pName = viewModel.pName,
                        pOperationType = viewModel.pOperationType,
                        pParent = viewModel.pParent,
                        pRemark = viewModel.pRemark,
                        pIsShow = viewModel.pIsShow
                    };
                    int n=OperationContext.Current.IBllSession.IPermissionBll
                        .Modify(permission,"pParent", "pName", "pAreaName", "pControllerName", "pActionName", "pFormMethod", "pIsShow", "pRemark");
                    return Redirect("~/Admin/System/Permission");
                }
            }
            LogHelper.WriteLog(typeof(SystemController), "EditPermission");
            return View("OperationError"); ;
        }

        public ActionResult AddPermission()
        {
            BuildDropDownList();
            return PartialView("AddPermission", new PermissionViewModel());
        }
        [HttpPost]
        public ActionResult AddPermission(PermissionViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                if (viewModel != null)
                {
                    Permission permission = new Permission()
                    {
                        pActionName = viewModel.pActionName,
                        pAddTime = DateTime.Now,
                        pAreaName = viewModel.pAreaName,
                        pControllerName = viewModel.pControllerName,
                        pFormMethod = viewModel.pFormMethod,
                        pName = viewModel.pName,
                        pOperationType = viewModel.pOperationType,
                        pParent = viewModel.pParent,
                        pRemark = viewModel.pRemark,
                        pIsShow = viewModel.pIsShow
                    };
                    int n = OperationContext.Current.IBllSession.IPermissionBll.Add(permission);
                    
                    //RolePermission rolePermission=new RolePermission()
                    //{
                    //    rpAddTime = DateTime.Now,
                    //    rpIsDel = false
                    //};
                    //Model.Permission permission1 = OperationContext.Current.IBllSession.IPermissionBll.GetListBy(
                    //    m =>
                    //        m.pAreaName == permission.pAreaName && m.pControllerName == permission.pControllerName &&
                    //        m.pActionName == permission.pActionName)
                    //    .FirstOrDefault();
                    //List<UserRole> userRoles = OperationContext.Current.CurrentUser.UserRole.ToList();
                    //if ((permission1 == null) || (userRoles.Count == 0))
                    //{
                    //    LogHelper.WriteLog(typeof(SystemController),"增加权限出错");
                    //    return View("OperationError"); 
                    //}
                    
                    //int n1=OperationContext.Current.IBllSession.IRolePermissionBll.Add()
                    return Redirect("~/Admin/System/Permission");
                }
            }
            LogHelper.WriteLog(typeof(SystemController), "AddPermission");
            return View("OperationError"); ;
        }

        [HttpPost]
        public ActionResult DeletePermission(int id)
        {
            MessageModel messageModel=new MessageModel();
            if (OperationContext.Current.IBllSession.IRolePermissionBll.GetListBy(m => m.rpPId == id).Count() != 0)
            {
                //主外键约束，不能删除权限
                messageModel.IsSuccess = false;
                messageModel.Message = "仍有角色在使用此权限，不能删除！";
                return Json(messageModel);
            }
            try
            {
                int n = OperationContext.Current
                .IBllSession.IPermissionBll.DeleteBy(m => m.pid == id);
                if (n<=0)
                {
                    messageModel.IsSuccess = false;
                    messageModel.Message = "删除失败!";
                }
            }
            catch (Exception e)
            {
                messageModel.IsSuccess = false;
                messageModel.Message = e.Message;
                throw;
            }
            return Json(messageModel);
        }
        /// <summary>
        ///生成DropDownList
        /// </summary>
        private void BuildDropDownList()
        {
            ViewBag.FormMethodList = new List<SelectListItem>()
            {
                new SelectListItem()
                {
                    Text = EnumFormMethod.Any.ToString(),
                    Value = ((int)EnumFormMethod.Any).ToString()
                },
                new SelectListItem()
                {
                    Text = EnumFormMethod.Get.ToString(),
                    Value = ((int)EnumFormMethod.Get).ToString()
                },
                new SelectListItem()
                {
                    Text =  EnumFormMethod.Post.ToString(),
                    Value = ((int)EnumFormMethod.Post).ToString()
                }
            };
            ViewBag.OperationType = new List<SelectListItem>()
            {
                new SelectListItem()
                {
                    Text = EnumOperationType.所有操作.ToString(),
                    Value = ((int)EnumOperationType.所有操作).ToString()
                },
                new SelectListItem()
                {
                    Text = EnumOperationType.EasyUI连接.ToString(),
                    Value = ((int)EnumOperationType.EasyUI连接).ToString()
                },
                new SelectListItem()
                {
                    Text = EnumOperationType.打开新窗口.ToString(),
                    Value = ((int)EnumOperationType.打开新窗口).ToString()
                }
            };
        }
    }
}
